package com.bajie.bjlisten.controller;

import com.alibaba.fastjson.JSONObject;
import com.bajie.bjlisten.api.UserCmsControllerApi;
import com.bajie.bjlisten.entity.*;
import com.bajie.bjlisten.entity.request.QueryUserRequest;
import com.bajie.bjlisten.entity.response.*;
import com.bajie.bjlisten.page.table.PageTableHandler;
import com.bajie.bjlisten.page.table.PageTableRequest;
import com.bajie.bjlisten.page.table.PageTableResponse;
import com.bajie.bjlisten.sevice.BjAdsService;
import com.bajie.bjlisten.sevice.BjInviteService;
import com.bajie.bjlisten.sevice.BjUserInterestService;
import com.bajie.bjlisten.sevice.BjUserService;
import com.bajie.bjlisten.utils.StringUtils;
import com.bajie.bjlisten.utils.UserUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/users")
public class BjUserController implements UserCmsControllerApi {

    @Autowired
    BjUserService bjUserService;
    @Autowired
    BjInviteService bjInviteService;

    @Autowired
    BjAdsService bjAdsService;

    @Autowired
    BjUserInterestService bjUserInterestService;

   /* *//**
     * 根据手机号码查询
     *
     * @param phone
     * @return
     *//*
    @GetMapping(value = "/bymobile/{phone}")
    public BjUser findByUserMobile(@PathVariable(name = "phone") Long phone) {


        return bjUserService.findByUserMobile(phone);
    }

    *//**
     * 根据用户ID查询
     *
     * @return
     *//*
    @GetMapping(value = "/byuserId/{userId}")
    public BjUser findByUserId(@PathVariable(name = "userId") String userId) {
        return bjUserService.findByUserId(userId);
    }

    *//**
     * 根据注册的开始时间段内查询
     *
     * @param beginRegister
     * @param endRegister
     * @return
     *//*
    @GetMapping(value = "/bytime/{beginRegister}/{endRegister}")
    public BjUserListResult findByRegisterTime(@PathVariable(name = "beginRegister") String beginRegister, @PathVariable(name = "endRegister") String endRegister) {

        return bjUserService.findByRegisterTime(beginRegister, endRegister);

    }

    *//**
     * 查询所有用户
     *
     * @return
     *//*
    @GetMapping(value = "/all")
    @ApiOperation(value = "查询所有用户", notes = "查询所有用户")
    public BjUserListResult findAll() {
        return bjUserService.findAll();
    }


    *//**
     * 根据用户名查询
     *//*
    @GetMapping(value = "/byusername/{userName}")
    public BjUser findByUserName(@PathVariable(name = "userName") String userName) {
        return bjUserService.findByUserName(userName);

    }

    *//**
     * 根据查询用户条件查询用户列表信息
     *
     * @param cond
     * @return
     *//*
    @PutMapping(value = "/cond/userinfo")
    public List<BjUser> findByCond(@RequestParam(required = false, value = "username") Map<String, String> cond) {
        QueryUserRequest queryUserRequest = new QueryUserRequest
                (cond.get("id"), cond.get("username"), Long.parseLong(cond.get("phone")),
                        cond.get("beginDate"), cond.get("endDate"));

        return bjUserService.findByCond(queryUserRequest);
    }

    *//**
     * 添加用户
     *
     * @param bjUser
     * @return
     *//*
    @PutMapping(value = "/addUser/{bjUser}")
    public BjUserListResult saveUserData(BjUser bjUser) {
        //TODO 判断用户是否拥有添加用户的权限
        //TODO 查询用户名是否存在
        int returnCode = bjUserService.saveUserData(bjUser);
        return new BjUserListResult(CommonCode.SUCCESS, returnCode);

    }

    *//**
     * 保存用户
     *
     * @param userDto
     * @return
     *//*
    @PostMapping("adduser")
   // @RequiresPermissions("sys:user:add")
    public BjUser saveUser(@RequestBody BjuserDto userDto) {
        BjUser u = bjUserService.findByUserName(userDto.getUsername());
        if (u != null) {
            throw new IllegalArgumentException(userDto.getUsername() + "已存在");
        }

        return bjUserService.saveUser(userDto);
    }

    *//**
     * 修改用户
     *
     * @param userDto
     * @return
     *//*
    @PutMapping("updateuser")
    //@RequiresPermissions("sys:user:add")
    public BjUser updateUser(@RequestBody BjuserDto userDto) {
        return bjUserService.updateUser(userDto);
    }

    *//**
     * 修改头像
     *
     * @param headImgUrl
     *//*
    @PutMapping(params = "headImgUrl")
    public void updateHeadImgUrl(String headImgUrl) {
        BjUser user = UserUtil.getCurrentUser();
        BjuserDto userDto = new BjuserDto();
        BeanUtils.copyProperties(user, userDto);
        userDto.setUserpic(headImgUrl);

        bjUserService.updateUser(userDto);
        log.debug("{}修改了头像", user.getUsername());
    }

    *//**
     * 修改密码
     *
     * @param username
     * @param oldPassword
     * @param newPassword
     *//*
    @PutMapping("/user/{username}")
    //@RequiresPermissions("sys:user:password")
    public void changePassword(@PathVariable String username, String oldPassword, String newPassword) {
        bjUserService.changePassword(username, oldPassword, newPassword);
    }

    *//**
     * 用户列表
     *
     * @param request
     * @return
     *//*

    @GetMapping
   // @RequiresPermissions("sys:user:query")
    public PageTableResponse listUsers(PageTableRequest request) {
        return new PageTableHandler(new PageTableHandler.CountHandler() {

            @Override
            public int count(PageTableRequest request) {
                return bjUserService.count(request.getParams());
            }
        }, new PageTableHandler.ListHandler() {

            public List<BjUser> list(PageTableRequest request) {
                List<BjUser> list = bjUserService.list(request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }


    *//**
     * 当前登录用户
     *
     * @return
     *//*
    @GetMapping("/current")
    public BjUser currentUser() {
        return UserUtil.getCurrentUser();
    }

    *//**
     * 根据用户id获取用户
     *
     * @param id
     * @return
     *//*
    @GetMapping("/{id}")
    //@RequiresPermissions("sys:user:query")
    public BjUser user(@PathVariable String id) {
        return bjUserService.findByUserId(id);
    }
*/

    // TODO 控制层少写业务，等到优化代码时候，放进业务层

    /**
     * 插入带入的emei/邀请码/唯一值，然后返回用户信息
     *
     * @param mapvalue
     * @return
     */
    @Transactional
    @PostMapping("/inserUserByImei")
    public BjUserResult getBjUserByImei(@RequestBody Map<String, String> mapvalue) {
        return bjUserService.getBjUserByImei(mapvalue);
    }

// TODO 控制层少写业务，等到优化代码时候，放进业务层

    /**
     * 第二次传入imei/或者唯一值
     * 根据imei更新用户信息[授权传参给后端]
     *
     * @param mapvalue
     * @return
     */
    @Transactional
    @PostMapping(value = "/updateImei")
    public BjUserResult updateByImei(@RequestBody Map<String, String> mapvalue) {
        return bjUserService.updateByTelImei(mapvalue);
    }


    @PostMapping(value = "/addInterest")
    public Boolean addInterestClassifys(@RequestBody BjClassifyDto bjClassifyDto) {

        return bjUserInterestService.addInterestClassifys(bjClassifyDto);

    }

    @PostMapping("/getcode")
    public ResponseResult getCode(@RequestParam("phoneNumber") String phoneNumber,@RequestParam("userId") String userId) {
        return bjUserService.getTelCode(phoneNumber,userId);
    }

    @Override
    @PostMapping("/userLoginByPhone")
    public ResponseResult userLoginByPhone(@RequestParam("userId") String userId,@RequestParam("phoneNumber") String phoneNumber, @RequestParam("yzCode")String yzCode) {

        return bjUserService.loginByPhone(userId,phoneNumber,yzCode);
    }

    /**
     * 根据用户查询被邀请的人
     * @param userId
     * @param offset
     * @param limit
     * @return
     */
    @PostMapping("/findAllByUserIds")
    public BjUserResult findAllByUserIds(@RequestParam("userId") String userId, @RequestParam("offset") Integer offset,@RequestParam("limit") Integer limit){
        return bjUserService.findAllByUserIds(userId, offset, limit);
    }
    @PostMapping("/findSumCoinByUserId")
    public JSONObject findSumCoinByUserId(@RequestParam("userId")  String userId){
        return bjUserService.findSumCoinByUserId(userId);
    }

}
